package com.tungse.callable_test;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class TestMyCallable2 {
    public static void main(String[] args) {
        System.out.println("主线程在执行任务");
        //1. 提供指定线程数量的线程池
        ExecutorService service = Executors.newFixedThreadPool(10);

        //2.执行指定的线程的操作。需要提供实现Runnable接口或Callable接口实现类的对象
        service.execute(new MyRunnable());//适合适用于Runnable

        try {
            Future<?> future = service.submit(new MyCallable());//适合使用于Callable
            System.out.println("偶数和为：" + future.get());
            System.out.println("Callable子线程执行完毕");
        } catch (Exception e) {
            e.printStackTrace();
        }
        //3.关闭连接池
        service.shutdown();
        System.out.println("所有任务执行完毕");
    }
}

class MyCallable implements Callable {
    //2.实现call方法，将此线程需要执行的操作声明在call()中
    @Override
    public Object call() {
        System.out.println("Callable子线程在进行计算偶数和");
        int evenSum = 0;
        for(int i = 0;i <= 100;i++){
            if(i % 2 == 0){
                evenSum += i;
            }
        }
        return evenSum;
    }
}
 
class MyRunnable implements Runnable{
    @Override
    public void run() {
        System.out.println("Runnable子线程在进行计算奇数和");
        int oddSum = 0;
        for(int i = 0;i <= 100;i++){
            if(i % 2 != 0){
                oddSum += i;
            }
        }
        System.out.println("奇数和为："+oddSum);
        System.out.println("Runnable子线程执行完毕");
    }
}
 
